package com.hwd.gmall.order.util;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取jwt令牌载荷信息的工具类
 *
 * @author 黄伟东/Victor
 * @date 2022/5/6 16:21
 */
public class TokenUtil {

    /** 公钥 */
    private static final String PUBLIC_KEY = "public.key";

    private static String publicKey = "";


    /**
     * 获取非对称加密公钥 Key
     *
     * @return java.lang.String 公钥 Key
     */
    public static String getPubKey() {

        if (!StringUtils.isEmpty(publicKey)) {
            return publicKey;
        }

        Resource resource = new ClassPathResource(PUBLIC_KEY);

        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            publicKey = br.lines().collect(Collectors.joining("\n"));
            return publicKey;
        } catch (IOException ioe) {
            return null;
        }
    }

    /**
     * 读取令牌数据
     *
     * @param token jwt令牌
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    public static Map<String, String> decodeToken(String token) {

        String pubKey = getPubKey();
        if (StringUtils.isEmpty(pubKey)) {
            return null;
        }

        // 校验Jwt
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(pubKey));

        // 获取Jwt原始内容
        String claims = jwt.getClaims();
        return JSON.parseObject(claims, Map.class);
    }
}
